package com.asiainfo.integration.actions;

import com.asiainfo.integration.queue.QueueDetails;
import com.asiainfo.integration.utils.ConfigProvider;
import org.apache.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Usage:
 *
 * @author Charkey
 * @date 2015/11/19
 */
@WebServlet(urlPatterns = "/dispatch", asyncSupported = true)
public class IndexDispatcher extends HttpServlet {

    public static final Logger INFO_LOG = Logger.getLogger(IndexDispatcher.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        INFO_LOG.debug("dispatch");

        String interfaceName = request.getParameter("interface_name");

        if (interfaceName != null) {
            QueueDetails queueDetails = ConfigProvider.getQueueDetailsMap().get(interfaceName);
            request.setAttribute("interface_name", queueDetails.getInterfaceName());
            request.setAttribute("initial_context_factory", queueDetails.getInitialContextFactory());
            request.setAttribute("connection_url", queueDetails.getConnectionUrl());
            request.setAttribute("connection_factory", queueDetails.getConnectionFactory());
            request.setAttribute("queue_name", queueDetails.getQueueName());
            request.setAttribute("username", queueDetails.getUsername());
            request.setAttribute("password", queueDetails.getPassword());
        }

        String method = request.getParameter("m");
        if (method.toLowerCase().equals("send")) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/pages/send.jsp");
            dispatcher.forward(request, response);
        } else if (method.toLowerCase().equals("receive")) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/pages/receive.jsp");
            dispatcher.forward(request, response);
        } else if (method.toLowerCase().equals("count")) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/pages/count.jsp");
            dispatcher.forward(request, response);
        } else if (method.toLowerCase().equals("rest_test")) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/pages/rest_test.jsp");
            dispatcher.forward(request, response);
        }
    }
}
